from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api.router import api_router
from app.core.config import settings
from fastapi.exceptions import RequestValidationError
from fastapi import HTTPException
from app.api.error_handlers import (
  http_exception_handler,
  validation_exception_handler,
  generic_exception_handler,
  response_validation_exception_handler,
)
from fastapi.exceptions import ResponseValidationError

from app.services.anniversary_scheduler import (
  start_anniversary_scheduler,
  stop_anniversary_scheduler,
)


def create_application() -> FastAPI:
  app = FastAPI(
    title=settings.app_name,
    debug=settings.debug,
    version="0.1.0",
    docs_url=settings.docs_url,
    openapi_url=settings.openapi_url,
    redirect_slashes=False,
  )

  allowed_origins = [
    "http://localhost:5173",
    "http://127.0.0.1:5173",
  ]
  app.add_middleware(
    CORSMiddleware,
    allow_origins=allowed_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["Authorization", "Content-Type", "Accept"],
    expose_headers=["Content-Type", "X-Thread-Id"],
    max_age=600,
  )

  # Unified error responses
  app.add_exception_handler(HTTPException, http_exception_handler)
  app.add_exception_handler(RequestValidationError, validation_exception_handler)
  app.add_exception_handler(ResponseValidationError, response_validation_exception_handler)
  app.add_exception_handler(Exception, generic_exception_handler)

  app.include_router(api_router, prefix=settings.api_v1_prefix)

  @app.on_event('startup')
  async def _startup() -> None:  # pragma: no cover - app lifecycle
    await start_anniversary_scheduler(app)

  @app.on_event('shutdown')
  async def _shutdown() -> None:  # pragma: no cover - app lifecycle
    await stop_anniversary_scheduler(app)
  return app


app = create_application()
